#encoding:utf-8
'''
Created on 2015年7月3日

@author: LWD
'''
import sys
import time
import requests
import ConfigParser
from bs4 import BeautifulSoup

session = None

_Zhihu_URL = 'http://www.zhihu.com'
_Captcha_URL_Prefix = _Zhihu_URL + '/captcha.gif?r='

def get_captcha_url():
    """获取验证码网址

    :return: 验证码网址
    :rtype: str
    """
    return _Captcha_URL_Prefix + str(int(time.time() * 1000))

def _save_captcha(url):
    global _session
    r = session.get(url)
    with open('code.gif', 'wb') as f:
        f.write(r.content)

def create_session():
    global session
    # 读取配置文件
    cf = ConfigParser.ConfigParser()
    cf.read("./config.ini")

    # 从配置文件读取 账号(e-mail)、 密码
    email = cf.get("info", "email")
    password = cf.get("info", "password")

    # 创建一个Session
    session = requests.Session()
    try:
        # 构造Http参数
        r = session.get('http://www.zhihu.com/')
        #print r.content
        _xsrf = BeautifulSoup(r.content).find(type='hidden')['value']
        
        url = get_captcha_url()
        _save_captcha(url)
        
        print('please check code.gif for captcha')
        captcha_num = raw_input('captcha: ')
        
        print captcha_num
        
        login_data = {"email": email, "password": password, "_xsrf":_xsrf, "captcha":captcha_num}
        header = {
            'User-Agent': "Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0",
            'Host': "www.zhihu.com",
            'Referer': "http://www.zhihu.com/"
        }
    
        r = session.post('http://www.zhihu.com/login/email', data=login_data, headers=header)
        # 根据post返回值，判断是否登录成功
        if r.json()["r"] == 1:
            print "Login Failed, reason is:"
            print r.json()["msg"]
            sys.exit(-1)
    except Exception as e:
        print "Login Failed, reason is:", e.message
        sys.exit(-1)
    return session
